package api

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"mxshop_api/order_web/global"
	"mxshop_api/order_web/utils"
	"net/http"
	"strings"
)

//将grpc的code转换成http的状态码
func HandleGrpcErrorToHttp(c *gin.Context, err error) {
	if err != nil {
		if e, ok := status.FromError(err); ok {
			switch e.Code() {
			case codes.NotFound:
				utils.ResJson(c, http.StatusNotFound, e.Message(), nil)
			case codes.Internal:
				utils.ResJson(c, http.StatusInternalServerError, "内部错误", nil)
			case codes.InvalidArgument:
				utils.ResJson(c, http.StatusBadRequest, "参数错误", nil)
			case codes.Unavailable:
				utils.ResJson(c, http.StatusInternalServerError, "服务不可用", nil)
			case codes.AlreadyExists:
				utils.ResJson(c, http.StatusInternalServerError, "已存在", nil)
			default:
				utils.ResJson(c, http.StatusInternalServerError, e.Code(), nil)
			}
			return
		}
	}
}

func removeTopStruct(fileds map[string]string) map[string]string {
	rsp := map[string]string{}
	for field, err := range fileds {
		rsp[field[strings.Index(field, ".")+1:]] = err
	}
	return rsp
}

//封装验证不通过的错误信息
func HandleValidatorError(c *gin.Context, err error) {
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		utils.ResJson(c, http.StatusOK, err.Error(), nil)
	}
	utils.ResJson(c, http.StatusBadRequest, removeTopStruct(errs.Translate(global.Trans)), nil)
}
